package com.example.partyplaner;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.Fragment;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class EventsActivity extends ListActivity implements AsyncResponse{

	ArrayAdapter<PartyEvent> adapter;
	List<PartyEvent> parties;
	DatabaseConnection db;
	private String responseMsg;
	private int responseCode;
	int logout=0;
	String filename="Events";
	FileOutputStream outputStream;
	FileInputStream inputStream;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		parties=new ArrayList<PartyEvent>();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_events);
		if(MainActivity.noInternetMode==0){
			this.db = new DatabaseConnection(EventsActivity.this);
			this.db.delegate = EventsActivity.this;
			db.execute("http://partyplanner.mais2014.cloudbees.net/rest/WebService/UserEvents", "GET", MainActivity.token);
		}
		else{
			try {
				FileInputStream fis;
				fis = openFileInput(filename);
				ObjectInputStream is = new ObjectInputStream(fis);
				parties = (ArrayList<PartyEvent>) is.readObject();
				is.close();
				adapter = new ArrayAdapter<PartyEvent>(this,android.R.layout.simple_list_item_1, parties);
				setListAdapter(adapter);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (StreamCorruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.events, menu);
		return true;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {

		Intent intent = new Intent(getApplicationContext(),SingleEventActivity.class);
		PartyEvent par=(PartyEvent) this.getListAdapter().getItem(position);
		intent.putExtra("EVENT_ID", Integer.toString(par.getId()));
		int idToPass = parties.get(position).getId();
		intent.putExtra("partyId", idToPass);
		//System.out.println("position" + position);
		//System.out.println("id = " + id);
		startActivity(intent);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.logout) {
			String status = NetworkUtil.getConnectivityStatusString(getApplicationContext());
			if(status!="Not connected to Internet"){
				this.db = new DatabaseConnection(EventsActivity.this);
				this.db.delegate = EventsActivity.this;
				db.execute("http://partyplanner.mais2014.cloudbees.net/rest/WebService/Logout", "GET", MainActivity.token);
				logout=1;
			}
			else{
				Toast toast=Toast.makeText(getApplicationContext(), "NO INTERNET CONNECTION", Toast.LENGTH_LONG);
		        LinearLayout toastLayout = (LinearLayout) toast.getView();
		        TextView toastTV = (TextView) toastLayout.getChildAt(0);
		        toastTV.setTextSize(30);
		        toastTV.setGravity(Gravity.CENTER_HORIZONTAL);
		        toast.show();
			}
				
		}
		return super.onOptionsItemSelected(item);
	}

	
	public void processFinish(WebserviceResponse output) {
		if(output!=null){
			responseCode=output.getResponseCode();
			if (responseCode==200){
				if (logout!=1)
				{
					responseMsg=output.getResponseMsg();
					try {		
						JSONArray jArray = new JSONArray(responseMsg);
						if (!jArray.isNull(0)){
							for (int it = 0; it<jArray.length(); it++) {
								JSONObject jObject= jArray.getJSONObject(it);
								PartyEvent party= new PartyEvent(Integer.parseInt(jObject.getString("eventID")),jObject.getString("eventName"));
								parties.add(party);
							}
								try {
									outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
									ObjectOutputStream os;
									os = new ObjectOutputStream(outputStream);
									os.writeObject(parties);
								} catch (IOException e) {
									e.printStackTrace();
								}				
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
					adapter = new ArrayAdapter<PartyEvent>(this,android.R.layout.simple_list_item_1, parties);
					setListAdapter(adapter);
				}
				else{
					Intent intent = new Intent(getApplicationContext(),MainActivity.class);
					startActivity(intent);
				}
			}
			else{
				Log.i("PartyPlanner", "Fail");
			}	
		}
		else{
			Log.i("PartyPlanner", "NULL");
		}
		
	// wywolanie jakiejs funkcji zapisujacej do pliku !
	}
	
	public Dialog onCreateDialog(int dialogId) {
		switch (dialogId) {
			case MainActivity.PLEASE_WAIT_DIALOG:
				ProgressDialog dialog = new ProgressDialog(EventsActivity.this);
				dialog.setTitle("Connecting");
				dialog.setMessage("Please wait....");
				dialog.setCancelable(true);
				return dialog;
			default:
				break;
		}
		return null;
	}
}
